//
//  VideoPlayer.swift
//  Swift-30-demo
//
//  Created by apple on 2021/12/1.
//

import UIKit
import AVFoundation
import AVKit
import MediaPlayer

class VideoPlayer: UIViewController {
    var audioPlayer: AVAudioPlayer?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "VideoPlayer"
        self.view.backgroundColor = UIColor.white
        // Do any additional setup after loading the view.
        
        createVideoSelectView()
    }
    
    func createVideoSelectView() {
        let videoButton = UIButton(type: .custom)
        videoButton.setTitle("Play Video", for: .normal)
        videoButton.setTitleColor(UIColor.white, for: .normal)
        videoButton.backgroundColor = UIColor.init(hexStr: "#FF3969")
        videoButton.layer.cornerRadius = 22
        videoButton.layer.masksToBounds = true
        videoButton.addTarget(self, action: #selector(playVideo), for: .touchUpInside)
        self.view.addSubview(videoButton)
        videoButton.snp.makeConstraints { make in
            make.top.equalTo(navgationHeight + 100)
            make.centerX.equalTo(self.view)
            make.width.equalTo(200)
            make.height.equalTo(44)
        }
        
        let audioPlayButton = UIButton(type: .custom)
        audioPlayButton.setTitle("Play Audio", for: .normal)
        audioPlayButton.setTitleColor(UIColor.white, for: .normal)
        audioPlayButton.backgroundColor = UIColor.init(hexStr: "#FF3969")
        audioPlayButton.layer.cornerRadius = 22
        audioPlayButton.layer.masksToBounds = true
        audioPlayButton.addTarget(self, action: #selector(playAudio), for: .touchUpInside)
        self.view.addSubview(audioPlayButton)
        audioPlayButton.snp.makeConstraints { make in
            make.top.equalTo(videoButton.snp.bottom).offset(100)
            make.centerX.equalTo(self.view)
            make.width.equalTo(200)
            make.height.equalTo(44)
        }
        
        let audioPauseButton = UIButton(type: .custom)
        audioPauseButton.setTitle("Pause Audio", for: .normal)
        audioPauseButton.setTitleColor(UIColor.white, for: .normal)
        audioPauseButton.backgroundColor = UIColor.init(hexStr: "#FF3969")
        audioPauseButton.layer.cornerRadius = 22
        audioPauseButton.layer.masksToBounds = true
        audioPauseButton.addTarget(self, action: #selector(pauseAudio), for: .touchUpInside)
        self.view.addSubview(audioPauseButton)
        audioPauseButton.snp.makeConstraints { make in
            make.top.equalTo(audioPlayButton.snp.bottom).offset(100)
            make.centerX.equalTo(self.view)
            make.width.equalTo(200)
            make.height.equalTo(44)
        }
        
        initAudio()
        UIApplication.shared.beginReceivingRemoteControlEvents()
        initForLockScreen()
    }
    
    @objc func playVideo() {
        let videoUrl = URL(string: "https://qn-video.ribenwawa.wang/dynamic/video/202112/16383646928441219.mp4")
        let player = AVPlayer(url: videoUrl!)
        let playerViewController = AVPlayerViewController()
        playerViewController.player = player
        self.present(playerViewController, animated: true) {}
    }
    
    @objc func playAudio() {
        audioPlayer?.play()
    }
    
    @objc func pauseAudio() {
        audioPlayer?.pause()
    }
    
    func initAudio() {
        let audioPath = Bundle.main.path(forResource: "live", ofType: "mp3")
        let audioUrl = URL(fileURLWithPath: audioPath!)
        
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: audioUrl)
        } catch {
            audioPlayer = nil
        }
        
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playAndRecord)
            try AVAudioSession.sharedInstance().setActive(true)
        } catch {
            print("error")
        }
    }
    
    func initForLockScreen() {
        let image = UIImage(named: "thumb.jpg")!
        MPNowPlayingInfoCenter.default().nowPlayingInfo = [
            MPMediaItemPropertyTitle : "皇后大道东",
            MPMediaItemPropertyArtist:"罗大佑",
            MPMediaItemPropertyArtwork:MPMediaItemArtwork.init(boundsSize: image.size, requestHandler: { (size) -> UIImage in
                return image
            }),
            MPNowPlayingInfoPropertyPlaybackRate:1.0,
            MPMediaItemPropertyPlaybackDuration:audioPlayer?.duration as Any,
            MPNowPlayingInfoPropertyElapsedPlaybackTime:audioPlayer?.currentTime as Any
        ]
    }
    
    override func remoteControlReceived(with event: UIEvent?) {
        switch event!.subtype {
        case .remoteControlPlay:
            audioPlayer?.play()
        case .remoteControlPause:
            audioPlayer?.pause()
        case .remoteControlStop:
            audioPlayer?.stop()
        default:
            break
        }
    }
}
